package com.FindMyStuff.Activities;

import com.FindMyStuff.Model.DataAccessor;
import com.FindMyStuff.Model.DataBaseHelper;
import com.FindMyStuff.Model.SessionManager;
import com.FindMyStuff.Model.User;
import com.FindMyStuff.Model.UserRole;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

public class CreateAdminActivity extends Activity {

	/**
	 * Holds the SessionManager so garbage collection will not get rid of the session manager
	 */
	@SuppressWarnings("unused")
	private SessionManager sm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_admin);
		sm = SessionManager.getInstance();
		Spinner spinner = (Spinner) findViewById(R.id.user_role);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
		        R.array.user_role_list, android.R.layout.simple_spinner_item);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_admin, menu);
		return true;
	}
	
	/**
	 * Attempts to create an Admin using the info in the text
	 * boxes
	 * @param view
	 */
	public void createAdmin(View view){
		EditText emailText = (EditText) findViewById(R.id.edit_email);
		EditText passwordText = (EditText) findViewById(R.id.edit_password);
		EditText confirmText = (EditText) findViewById(R.id.confirm_password);
		
		String email = emailText.getText().toString();
		String password = passwordText.getText().toString();
		String confirm = confirmText.getText().toString();
		String errors = checkPassword(password, confirm);
		Spinner userRole = (Spinner) findViewById(R.id.user_role);
		
		if(!checkEmail(email)){
			errors = "Invalid email address.\n" +errors;
		}
		if(errors.equals("")){
			//not sure if we'll manually jump back or not
			//Intent intent = new Intent(this, AdminHomeActivity.class);
			DataBaseHelper dbh = new DataBaseHelper(this);
			DataAccessor da = new DataAccessor(dbh);
			UserRole role = UserRole.convertStringtoRole(userRole.getSelectedItem().toString());
			User user = da.createUser(email, password, role);
			if(user.exist() == false)
			{
				errors = "Email address is already in use. \n";
			} else 
			{
				Dialog success =  createSuccessfulDialog();
				success.show();				
				Intent intent = new Intent(this, AdminHomeActivity.class);
				startActivity(intent);
			}
		}
		if(errors.equals("") == false){
			Dialog errorDialog = createIncorrectDialog(errors);
			errorDialog.show();
		}
	}
	
	/**
	 * Checks the email address that is passed in
	 * using regular expressions
	 * @param email The email to be checked
	 * @return true if valid, else false
	 */
	
	public boolean checkEmail(String email){
		return email.matches("[A-Za-z0-9]+[@][A-Za-z0-9]+(.com|.net|.edu)");
	}
	
	/**
	 * Checks a given password and returns any errors that are found
	 * 
	 * @param password The password to be checked
	 * @param confirm Contents of the confirm password box
	 * @return A string of the errors found
	 */
	public String checkPassword(String password, String confirm){
		String errors = "";
		if(!password.equals(confirm)){
			errors +="Passwords do not match.\n";
		}
		if(password.length()<5 || password.length()>13){
			errors += "Password should be between 5 and 13 characters.\n";
		}
		//regular expression for uppercase and lowercase letters
		//and numbers
		if(!password.matches("[A-Za-z0-9]*")){
			errors += "Password should only be made of letters and numbers.\n";
		}
		
		return errors;
	}
	
	/**
	 * Creates a Dialog to display the errors found while
	 * checking the email and password
	 * 
	 * @param error The string containing all of the errors
	 * @return The Dialog object to be displayed
	 */
	
	public Dialog createIncorrectDialog(String error) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage(error);
	    builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	                   
	               }
	           });
	    return builder.create();
	}
	
	/**
	 * Lets the user know that the log in was successful
	 * Dialog box changes current page to LogInActivity
	 * when the ok button is pressed
	 * 
	 * @param i An Intent object to transfer to LogInActivity
	 * @return The Dialog object to be used on successful login
	 */
	public Dialog createSuccessfulDialog() {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage("The new User has been created successfully.");
	    builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	            	   
	               }
	           });
	    return builder.create();
	}

}
